
package com.goldsand.collaboration.handoff;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.TextView;

import com.goldsand.collaboration.handoff.client.connection.SocketClientService;
import com.goldsand.collaboration.handoff.client.connection.SocketClientService.MyClientBinder;
import com.goldsand.collaboration.handoff.common.connection.NewMessageListener;
import com.goldsand.collaboration.handoff.common.connection.Utils;

public class TestClientActivity extends Activity implements ServiceConnection, NewMessageListener {
    private TextView textView;
    private SocketClientService socketService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.textView);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!Utils.isCurrentAppTypeServer(TestClientActivity.this)) {
            Intent intent = SocketClientService.createClientInIntent();
            startService(intent);
            bindService(intent, this, BIND_AUTO_CREATE);
            Message message2 = handler.obtainMessage();
            message2.obj = "client connection";
            message2.sendToTarget();
        }
    }

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            String text = (String) msg.obj;
            textView.append(text+"\n");
        };
    };
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        socketService = ((MyClientBinder) service).getService();
        socketService.addMessageListener(this);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onNewMessageReceived(String threadName, String message) {
        Message message2 = handler.obtainMessage();
        message2.obj = message;
        message2.sendToTarget();
    }

}
